package com.andy.qhb.game;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import com.google.common.collect.Lists;

/**
 * 循环列表
 * @author cuiwm
 *
 */
public class LoopList<T> {
	
	private static final int ExpectedSize = 2048;
	
	public static final int LIMIT = 20;
	
	private List<T> list = Lists.newArrayListWithCapacity(ExpectedSize);
	
	private AtomicInteger curIndex = new AtomicInteger(0);
	
	public LoopList() {
		for(int i=0;i<ExpectedSize;i++) {
			list.add(null);
		}
	}
	
	/**
	 * 最大可读指针
	 * @return
	 */
	public int endIndx(){
		return curIndex.get();
	}
	
	/**
	 * 获取范围列表
	 * @param start
	 * @param end
	 * @return
	 */
	public List<T> subList(int start,int end) {
		if(end > curIndex.get()) return null;
		if(start < end - LIMIT) start = end-LIMIT;
		start = start % ExpectedSize;
		end = end % ExpectedSize;
		if(start > end) {
			// 超过了容量回到起点
			List<T> res = Lists.newArrayList();
			res.addAll(list.subList(start, list.size()));
			res.addAll(list.subList(0, end));
			return res;
		}
		return list.subList(start, end);
	}
	
	/**
	 * 新增元素
	 * @param game
	 */
	public void add(T game){
		int i = curIndex.getAndIncrement();
		i = i%ExpectedSize;
		if(list.size() <= i){
			list.add(game);
		}else {
			list.set(i, game);
		}
	}

	
}

